package com.attedu.jdbc;

import com.attedu.jdbc.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author tune_the last
 * @date 2025/11/4 - 11:40
 * 返回响应
 * 1.注册成功
 * 2.用户名被占用，请换一个
 */
public class JDBCReg {
    public static void main(String[] args) {
        try(Connection connection = DBUtil.getConnection();) {
            String querySql = "SELECT id FROM user WHERE username = ?";
            PreparedStatement ps1 = connection.prepareStatement(querySql);
            Scanner in = new Scanner(System.in);
            System.out.print("请输入用户名：");
            String username = in.nextLine();
            ps1.setString(1, username);
            ResultSet resultSet = ps1.executeQuery();
            if (resultSet.next()){
                System.out.println("用户名已存在，请重新输入");
                return;
            }
            String insertSql = "INSERT INTO user(username, password, nickname, age) VALUES (?,?,?,?)";
            PreparedStatement ps2 = connection.prepareStatement(insertSql);
            ps2.setString(1, username);
            System.out.print("请输入密码：");
            ps2.setString(2, in.nextLine());
            System.out.print("请输入昵称：");
            ps2.setString(3, in.nextLine());
            System.out.print("请输入年龄：");
            ps2.setInt(4, in.nextInt());
            int i = ps2.executeUpdate();
            if (i > 0){
                System.out.println("注册成功");
            }else {
                System.out.println("注册失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
